package com.ruoyi.mp.service.impl;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.db.domain.system.*;
import com.ruoyi.db.domain.web.MpIncomeRecord;
import com.ruoyi.db.mapper.system.*;
import com.ruoyi.db.mapper.web.MpIncomeRecordMapper;
import com.ruoyi.mp.service.IPcRaiseConfigService;
import com.ruoyi.mp.service.IPcRaiseService;
import com.ruoyi.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 众筹活动Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-08-03
 */
@Service
@Transactional(rollbackOn = Exception.class)
public class PcRaiseServiceImpl implements IPcRaiseService
{
    @Autowired
    private PcRaiseMapper pcRaiseMapper;
    @Autowired
    private MpClientRaiseRecordMapper mpClientRaiseRecordMapper;
    @Autowired
    private PcRaiseRecordMapper pcRaiseRecordMapper;
    @Autowired
    private MpClientMapper mpClientMapper;
    @Autowired
    private MpClientFriendsMapper mpClientFriendsMapper;
    @Autowired
    private MpClientEarnsMapper mpClientEarnsMapper;
    @Autowired
    private PcTeamConfigMapper pcTeamConfigMapper;
    @Autowired
    private MpIncomeRecordMapper mpIncomeRecordMapper;
    @Autowired
    private PcRaiseSystemConfigMapper pcRaiseSystemConfigMapper;
    @Autowired
    private PcCardMapper pcCardMapper;
    @Autowired
    private PcClientReturnRecordMapper pcClientReturnRecordMapper;
    @Autowired
    private MpClientReturnRecordMapper mpClientReturnRecordMapper;
    @Autowired
    PcReturnConfigMapper pcReturnConfigMapper;
    @Autowired
    PcUserClientFriendsMapper pcUserClientFriendsMapper;
    @Autowired
    PcUserEarnsMapper pcUserEarnsMapper;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    IPcRaiseConfigService pcRaiseConfigService;
    @Autowired
    PcDistributionConfigMapper pcDistributionConfigMapper;
    @Autowired
    PcCompanyConfigMapper pcCompanyConfigMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private PcRaiseConfigMapper pcRaiseConfigMapper;

    /**
     * 查询众筹活动
     * 
     * @param id 众筹活动主键
     * @return 众筹活动
     */
    @Override
    public PcRaise selectPcRaiseById(Long id)
       {
        Date now = new Date();
        PcRaise raise = pcRaiseMapper.selectPcRaiseById(id);
        MpClientRaiseRecord clientRaiseRecord = new MpClientRaiseRecord();
        clientRaiseRecord.setRaiseId(raise.getId());
        List<MpClientRaiseRecord> clientRaiseRecords = mpClientRaiseRecordMapper.selectMpClientRaiseRecordList(clientRaiseRecord);
        if(clientRaiseRecords.size()==0){
            raise.setTakeRate(new BigDecimal(0));
            raise.setTakeAmount(new BigDecimal(0));
            raise.setOrderAmount(new BigDecimal("0"));
        }else{
            BigDecimal myTakeSum = clientRaiseRecords.stream().map( MpClientRaiseRecord:: getTakeAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
            raise.setTakeRate(myTakeSum.divide(raise.getTotalAmount(),2,BigDecimal.ROUND_DOWN));
            raise.setTakeAmount(myTakeSum);
            BigDecimal orderSum = clientRaiseRecords.stream().filter(e->e.getOrderAmount()!=null).map( MpClientRaiseRecord:: getOrderAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
            raise.setOrderAmount(orderSum);
        }
        if(raise.getIsSuccess()==0&&raise.getIsOver()==1){
            raise.setRaiseStatus(1);
        }
        if(raise.getIsSuccess()==1&&raise.getIsOver()==1){
            raise.setRaiseStatus(2);
        }
       if(raise.getIsSuccess()==0&&raise.getIsOver()==0){
           if(raise.getTakeAmount().compareTo(raise.getTotalAmount())>=0){
                //如果参与金额达到活动金额,并且当前时间在预约-开始时间之内。设定状态为预约已满
               if(now.after(raise.getOrderTime())&&now.before(raise.getStartTime())){
                   raise.setRaiseStatus(3);
               }
               if(now.after(raise.getStartTime())&&now.before(raise.getContinueTime())){
                   //参与金额已满
                   raise.setRaiseStatus(2);
               }
           }else{
               //立即预约
               if(now.after(raise.getFirstOrderTime())&&now.before(raise.getStartTime())){
                   raise.setRaiseStatus(5);
               }
               //优先预约
               if(now.after(raise.getOrderTime())&&now.before(raise.getFirstOrderTime())){
                   raise.setRaiseStatus(6);
               }
               if(now.after(raise.getStartTime())&&now.before(raise.getContinueTime())){
                   //参与游戏
                   raise.setRaiseStatus(7);
               }
           }

       }
        return raise;
    }

    public static void main(String[] args) {
        BigDecimal a= new BigDecimal("3963");
        BigDecimal b= new BigDecimal("5662");
        System.out.println(a.divide(b,2,BigDecimal.ROUND_DOWN));

    }
    @Override
    public  BigDecimal getShare(PcRaise pcRaise) {
        PcRaiseRecord sRecord = new PcRaiseRecord();
        sRecord.setRaiseType(pcRaise.getRaiseType());
        PcRaiseRecord raiseRecord = pcRaiseRecordMapper.selectMpLastSuccessPcRaiseRecord(sRecord);
        return raiseRecord==null?new BigDecimal(0):raiseRecord.getAddShareAmount();
    }

    /**
     * 查询众筹活动列表
     * 
     * @param pcRaise 众筹活动
     * @return 众筹活动
     */
    @Override
    public List<PcRaise> selectPcRaiseList(PcRaise pcRaise)
    {
        Date now =new Date();
        List<PcRaise> list = pcRaiseMapper.selectMpRaiseList(pcRaise);
        for (PcRaise raise:list) {
            MpClientRaiseRecord clientRaiseRecord = new MpClientRaiseRecord();
            clientRaiseRecord.setRaiseId(raise.getId());
            List<MpClientRaiseRecord> clientRaiseRecords = mpClientRaiseRecordMapper.selectMpClientRaiseRecordList(clientRaiseRecord);
           if(clientRaiseRecords.size()==0){
               raise.setTakeRate(new BigDecimal(0));
               raise.setTakeAmount(new BigDecimal(0));
           }else{
               BigDecimal myTakeSum = clientRaiseRecords.stream().map( MpClientRaiseRecord:: getTakeAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
               raise.setTakeRate(myTakeSum.divide(raise.getTotalAmount(),2,BigDecimal.ROUND_DOWN));
               raise.setTakeAmount(myTakeSum);
           }
            if(raise.getIsSuccess()==0&&raise.getIsOver()==1){
                raise.setRaiseStatus(1);
            }
            if(raise.getIsSuccess()==1&&raise.getIsOver()==1){
                //如果游戏成功并结束,并结算了收益
                MpClientRaiseRecord raiseRecord = new MpClientRaiseRecord();
                raiseRecord.setRaiseId(raise.getId());
                List<MpClientRaiseRecord> list1 = mpClientRaiseRecordMapper.selectMpClientRaiseRecordList(raiseRecord);
                if(list1.get(0).getSettlementTime()!=null){
                    raise.setRaiseStatus(2);
                }else{
                    raise.setRaiseStatus(3);
                }
            }
            if(raise.getIsSuccess()==0&&raise.getIsOver()==0){
                if(now.after(raise.getStartTime())&&now.before(raise.getContinueTime())){
                    MpClientRaiseRecord raiseRecord = new MpClientRaiseRecord();
                    raiseRecord.setRaiseId(raise.getId());
                    List<MpClientRaiseRecord> list1 = mpClientRaiseRecordMapper.selectMpClientRaiseRecordList(raiseRecord);
                    BigDecimal takeSum = list1.stream().map( MpClientRaiseRecord:: getTakeAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
                    if(raise.getTotalAmount().compareTo(takeSum)>0){
                        raise.setRaiseStatus(5);
                    }else{
                        raise.setRaiseStatus(7);
                    }
                }
                if(now.after(raise.getFirstOrderTime())&&now.before(raise.getStartTime())){
                    raise.setRaiseStatus(4);
                }
                if(now.before(raise.getFirstOrderTime())&&now.after(raise.getOrderTime())){
                    raise.setRaiseStatus(6);
                }

            }
        }
        return list;
    }

    /**
     * 新增众筹活动
     * 
     * @param pcRaise 众筹活动
     * @return 结果
     */
    @Override
    public int insertPcRaise(PcRaise pcRaise)
    {
        pcRaise.setCreateTime(DateUtils.getNowDate());
        return pcRaiseMapper.insertPcRaise(pcRaise);
    }

    /**
     * 修改众筹活动
     * 
     * @param pcRaise 众筹活动
     * @return 结果
     */
    @Override
    public int updatePcRaise(PcRaise pcRaise)
    {
        return pcRaiseMapper.updatePcRaise(pcRaise);
    }

    /**
     * 批量删除众筹活动
     * 
     * @param ids 需要删除的众筹活动主键
     * @return 结果
     */
    @Override
    public int deletePcRaiseByIds(Long[] ids)
    {
        return pcRaiseMapper.deletePcRaiseByIds(ids);
    }

    /**
     * 删除众筹活动信息
     * 
     * @param id 众筹活动主键
     * @return 结果
     */
    @Override
    public int deletePcRaiseById(Long id)
    {
        return pcRaiseMapper.deletePcRaiseById(id);
    }

    @Override
    public void settleByOverTime() {
        Date now = new Date();
        SimpleDateFormat sdfTwo = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
        String time = sdfTwo.format(now);

        List<PcRaiseConfig> configss = pcRaiseConfigMapper.selectPcRaiseConfigListAble();
        for (PcRaiseConfig pcRaiseConfig:configss) {
            Long type = pcRaiseConfig.getRaiseType().longValue();
            System.out.println("计算活动1"+"RAISE_"+type+"_"+time);
            if(!redisService.hasKey("RAISE_"+type+"_"+time)){
                continue;
            }
            System.out.println("计算活动2"+"RAISE_"+type+"_"+time);
            Long raiseId =  redisService.getCacheObject("RAISE_"+type+"_"+time);
            //获取最新一期活动结束时间
            PcRaise raise = pcRaiseMapper.selectPcRaiseById(raiseId);
            if(raise==null){
                continue;
            }
            if(type!=raise.getRaiseType()){
                continue;
            }
            Date endTime = raise.getContinueTime();
            if(!sdfTwo.format(endTime).equals(sdfTwo.format(now))){
                continue;
            }
            //获取参与该期活动用户,判断是否众筹成功
            MpClientRaiseRecord mpClientRaiseRecord = new MpClientRaiseRecord();
            mpClientRaiseRecord.setRaiseId(raise.getId());
            List<MpClientRaiseRecord> mpClientRaiseRecords =
                    mpClientRaiseRecordMapper.selectMpClientRaiseRecordList(mpClientRaiseRecord);
            //获取用户参与的总金额(包括预购和现购)
            BigDecimal takeSum = mpClientRaiseRecords.stream().map( MpClientRaiseRecord:: getTakeAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型

            if(raise.getTotalAmount().compareTo(takeSum)>0){
                //获取活动失败返还金藻比例设置
                PcRaiseSystemConfig pcRaiseSystemConfig = new PcRaiseSystemConfig();
                List<PcRaiseSystemConfig> pcRaiseSystemConfigs = pcRaiseSystemConfigMapper.selectPcRaiseSystemConfigList(pcRaiseSystemConfig);
                BigDecimal lockGoldRate = pcRaiseSystemConfigs.get(0).getLockReturnGoldRate();
                //获取活动失败返还银藻比例
                BigDecimal lockSilverRate = pcRaiseSystemConfigs.get(0).getLockReturnSilverRate();
                //获取活动失败返还当前金藻比例
                BigDecimal nowGoldRate = pcRaiseSystemConfigs.get(0).getNowReturnGoldRate();
                //活动失败 返还当期所有用户参与金额+奖金池分红按用户参与金额比例分发
                //获取活动上期奖金池累积金额
                PcRaiseRecord pcRaiseRecord = new PcRaiseRecord();
                pcRaiseRecord.setRaiseType(raise.getRaiseType());
                pcRaiseRecord.setSettleTime(raise.getContinueTime());
                PcRaiseRecord lastRecord = pcRaiseRecordMapper.selectLastSuccessPcRaiseRecord(pcRaiseRecord);
                //参与用户按ID分组
                Map<Long, List<MpClientRaiseRecord>> map = mpClientRaiseRecords.stream()
                        .collect(Collectors.groupingBy(MpClientRaiseRecord::getClientId));

                if(lastRecord!=null&&lastRecord.getIsSuccess()==1){
                    //上期活动成功,分红池累积金额加权分发给用户
                    BigDecimal addAmount = lastRecord.getAddShareAmount();
                    for (Long key : map.keySet()){
                        //返还用户参与的金额
                        MpClient mpClient = mpClientMapper.selectMpClientByClientId(key);
                        List<MpClientRaiseRecord> myRecord = map.get(key);
                        BigDecimal myTakeSum = myRecord.stream().map( MpClientRaiseRecord:: getTakeAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
                        mpClient.setGoldBeanBalance(mpClient.getGoldBeanBalance()==null?new BigDecimal(0):
                                mpClient.getGoldBeanBalance().add(myTakeSum.multiply(nowGoldRate).setScale( 2, BigDecimal.ROUND_HALF_UP )));
                        mpClientMapper.updateMpClient(mpClient);
                        //增加用户金藻收益记录
                        MpIncomeRecord mpIncomeRecord = new MpIncomeRecord();
                        mpIncomeRecord.setIsIncome(1l);
                        mpIncomeRecord.setType(1l);
                        mpIncomeRecord.setCreateTime(now);
                        mpIncomeRecord.setClientId(mpClient.getClientId());
                        mpIncomeRecord.setContent(raise.getRaiseName()+"第"+raise.getListCount()+"期"+"活动失败返还参与金藻");
                        mpIncomeRecord.setAmount(myTakeSum.multiply(nowGoldRate).setScale( 2, BigDecimal.ROUND_HALF_UP ));
                        mpIncomeRecord.setCurrentBalance(mpClient.getGoldBeanBalance());
                        mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecord);

                        //分红池金额按参与金额比例分给用户

                        BigDecimal shareAmount = myTakeSum.divide(takeSum,2,BigDecimal.ROUND_HALF_UP).multiply(addAmount).setScale( 2, BigDecimal.ROUND_HALF_UP );
                        mpClient.setGoldBeanBalance(mpClient.getGoldBeanBalance()==null?new BigDecimal(0):
                                mpClient.getGoldBeanBalance().add(shareAmount));
                        mpClientMapper.updateMpClient(mpClient);
                        //增加用户金藻收益记录
                        MpIncomeRecord mpIncomeRecordT = new MpIncomeRecord();
                        mpIncomeRecordT.setIsIncome(1l);
                        mpIncomeRecordT.setType(1l);
                        mpIncomeRecordT.setCreateTime(now);
                        mpIncomeRecordT.setClientId(mpClient.getClientId());
                        mpIncomeRecordT.setContent(raise.getRaiseName()+"第"+raise.getListCount()+"期"+"活动失败奖金池分红");
                        mpIncomeRecordT.setAmount(shareAmount);
                        mpIncomeRecordT.setCurrentBalance(mpClient.getGoldBeanBalance());
                        mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecordT);
                        //更新用户参与记录表
                        for (MpClientRaiseRecord r:myRecord) {
                            r.setSettlementTime(now);
                            r.setGetGoldAmount(shareAmount.add(myTakeSum.multiply(nowGoldRate).setScale( 2, BigDecimal.ROUND_HALF_UP )));
                            r.setGetSilverAmount(new BigDecimal(0));
//                        r.setIsSettleEarns(1);
                            mpClientRaiseRecordMapper.updateMpClientRaiseRecord(r);
                        }
                    }
                    //获取上期活动参与用户,分发65%金藻+35%银藻给相应用户
                    MpClientRaiseRecord lastMpClientRaiseRecord = new MpClientRaiseRecord();
                    lastMpClientRaiseRecord.setRaiseId(lastRecord.getRaiseId());
                    List<MpClientRaiseRecord> lastMpClientRaiseRecords =
                            mpClientRaiseRecordMapper.selectMpClientRaiseRecordList(lastMpClientRaiseRecord);

                    //上期成功参与用户按ID分组
                    Map<Long, List<MpClientRaiseRecord>> mapLast = lastMpClientRaiseRecords.stream()
                            .collect(Collectors.groupingBy(MpClientRaiseRecord::getClientId));
                    for (Long keyLast : mapLast.keySet()){
                        MpClient mpClientLast = mpClientMapper.selectMpClientByClientId(keyLast);
                        List<MpClientRaiseRecord> myRecordLast = mapLast.get(keyLast);
                        BigDecimal myTakeSum = myRecordLast.stream().map( MpClientRaiseRecord:: getTakeAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
                        mpClientLast.setGoldBeanBalance(mpClientLast.getGoldBeanBalance()==null?new BigDecimal(0):
                                mpClientLast.getGoldBeanBalance().add(myTakeSum.multiply(lockGoldRate).setScale( 2, BigDecimal.ROUND_HALF_UP )));
                        mpClientLast.setSilverBeanBalance(mpClientLast.getSilverBeanBalance()==null?new BigDecimal(0):
                                mpClientLast.getSilverBeanBalance().add(myTakeSum.multiply(lockSilverRate).setScale( 2, BigDecimal.ROUND_HALF_UP )));
                        mpClientMapper.updateMpClient(mpClientLast);
                        //增加用户金藻收益记录
                        MpIncomeRecord mpIncomeRecord = new MpIncomeRecord();
                        mpIncomeRecord.setIsIncome(1l);
                        mpIncomeRecord.setType(1l);
                        mpIncomeRecord.setCreateTime(now);
                        mpIncomeRecord.setClientId(mpClientLast.getClientId());
                        mpIncomeRecord.setContent(raise.getRaiseName()+"第"+raise.getListCount()+"期"+"活动失败返还参与金藻");
                        mpIncomeRecord.setAmount(myTakeSum.multiply(lockGoldRate).setScale( 2, BigDecimal.ROUND_HALF_UP ));
                        mpIncomeRecord.setCurrentBalance(mpClientLast.getGoldBeanBalance());
                        mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecord);

                        //增加用户金藻收益记录
                        MpIncomeRecord mpIncomeRecordS = new MpIncomeRecord();
                        mpIncomeRecordS.setIsIncome(1l);
                        mpIncomeRecordS.setType(2l);
                        mpIncomeRecordS.setCreateTime(now);
                        mpIncomeRecordS.setClientId(mpClientLast.getClientId());
                        mpIncomeRecordS.setContent(raise.getRaiseName()+"第"+raise.getListCount()+"期"+"活动失败返还银藻");
                        mpIncomeRecordS.setAmount(myTakeSum.multiply(lockSilverRate).setScale( 2, BigDecimal.ROUND_HALF_UP ));
                        mpIncomeRecordS.setCurrentBalance(mpClientLast.getGoldBeanBalance());
                        mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecordS);
                        //更新上期用户参与记录表
                        for (MpClientRaiseRecord r:myRecordLast) {
                            r.setSettlementTime(now);
                            r.setGetGoldAmount(myTakeSum.multiply(lockGoldRate).setScale( 2, BigDecimal.ROUND_HALF_UP ));
                            r.setGetSilverAmount(myTakeSum.multiply(lockSilverRate).setScale( 2, BigDecimal.ROUND_HALF_UP ));
//                        r.setIsSettleEarns(1);
                            mpClientRaiseRecordMapper.updateMpClientRaiseRecord(r);
                        }
                    }
                    //获取活动上上期活动记录
                    PcRaiseRecord pcRaiseRecordLast = new PcRaiseRecord();
                    pcRaiseRecordLast.setRaiseType(lastRecord.getRaiseType());
                    pcRaiseRecordLast.setSettleTime(lastRecord.getSettleTime());
                    PcRaiseRecord lastLastRecord = pcRaiseRecordMapper.selectLastSuccessPcRaiseRecord(pcRaiseRecordLast);
                    if(lastLastRecord!=null&&lastLastRecord.getIsSuccess()==1){
                        //获取上上期活动参与用户,分发65%金藻+35%银藻给相应用户
                        MpClientRaiseRecord lastLastMpClientRaiseRecord = new MpClientRaiseRecord();
                        lastLastMpClientRaiseRecord.setRaiseId(lastLastRecord.getRaiseId());
                        List<MpClientRaiseRecord> lastLastMpClientRaiseRecords =
                                mpClientRaiseRecordMapper.selectMpClientRaiseRecordList(lastLastMpClientRaiseRecord);

                        //上期成功参与用户按ID分组
                        Map<Long, List<MpClientRaiseRecord>> mapLastLast = lastLastMpClientRaiseRecords.stream()
                                .collect(Collectors.groupingBy(MpClientRaiseRecord::getClientId));
                        for (Long keyLast : mapLastLast.keySet()){
                            MpClient mpClientLast = mpClientMapper.selectMpClientByClientId(keyLast);
                            List<MpClientRaiseRecord> myRecordLast = mapLastLast.get(keyLast);
                            BigDecimal myTakeSum = myRecordLast.stream().map( MpClientRaiseRecord:: getTakeAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
                            mpClientLast.setGoldBeanBalance(mpClientLast.getGoldBeanBalance()==null?new BigDecimal(0):
                                    mpClientLast.getGoldBeanBalance().add(myTakeSum.multiply(lockGoldRate).setScale( 2, BigDecimal.ROUND_HALF_UP )));
                            mpClientLast.setSilverBeanBalance(mpClientLast.getSilverBeanBalance()==null?new BigDecimal(0):
                                    mpClientLast.getSilverBeanBalance().add(myTakeSum.multiply(lockSilverRate).setScale( 2, BigDecimal.ROUND_HALF_UP )));
                            mpClientMapper.updateMpClient(mpClientLast);

                            //增加用户金藻收益记录
                            MpIncomeRecord mpIncomeRecord = new MpIncomeRecord();
                            mpIncomeRecord.setIsIncome(1l);
                            mpIncomeRecord.setType(1l);
                            mpIncomeRecord.setCreateTime(now);
                            mpIncomeRecord.setClientId(mpClientLast.getClientId());
                            mpIncomeRecord.setContent(raise.getRaiseName()+"第"+raise.getListCount()+"期"+"活动失败返还参与金藻");
                            mpIncomeRecord.setAmount(myTakeSum.multiply(lockGoldRate).setScale( 2, BigDecimal.ROUND_HALF_UP ));
                            mpIncomeRecord.setCurrentBalance(mpClientLast.getGoldBeanBalance());
                            mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecord);

                            //增加用户金藻收益记录
                            MpIncomeRecord mpIncomeRecordS = new MpIncomeRecord();
                            mpIncomeRecordS.setIsIncome(1l);
                            mpIncomeRecordS.setType(2l);
                            mpIncomeRecordS.setCreateTime(now);
                            mpIncomeRecordS.setClientId(mpClientLast.getClientId());
                            mpIncomeRecordS.setContent(raise.getRaiseName()+"第"+raise.getListCount()+"期"+"活动失败返还银藻");
                            mpIncomeRecordS.setAmount(myTakeSum.multiply(lockSilverRate).setScale( 2, BigDecimal.ROUND_HALF_UP ));
                            mpIncomeRecordS.setCurrentBalance(mpClientLast.getGoldBeanBalance());
                            mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecordS);

                            //更新上期用户参与记录表
                            for (MpClientRaiseRecord r:myRecordLast) {
                                r.setSettlementTime(now);
                                r.setGetGoldAmount(myTakeSum.multiply(lockGoldRate).setScale( 2, BigDecimal.ROUND_HALF_UP ));
                                r.setGetSilverAmount(myTakeSum.multiply(lockSilverRate).setScale( 2, BigDecimal.ROUND_HALF_UP ));
//                            r.setIsSettleEarns(1);
                                mpClientRaiseRecordMapper.updateMpClientRaiseRecord(r);
                            }
                        }
                        //获取活动上上上期活动记录
                        PcRaiseRecord pcRaiseRecordLastLast = new PcRaiseRecord();
                        pcRaiseRecordLastLast.setRaiseType(lastLastRecord.getRaiseType());
                        pcRaiseRecordLastLast.setSettleTime(lastLastRecord.getSettleTime());
                        PcRaiseRecord lastLastLastRecord = pcRaiseRecordMapper.selectLastSuccessPcRaiseRecord(pcRaiseRecordLastLast);
                        if(lastLastLastRecord!=null&&lastLastLastRecord.getIsSuccess()==1){
                            //获取上上上期活动参与用户,分发65%金藻+35%银藻给相应用户
                            MpClientRaiseRecord lastLastLastMpClientRaiseRecord = new MpClientRaiseRecord();
                            lastLastLastMpClientRaiseRecord.setRaiseId(lastLastLastRecord.getRaiseId());
                            List<MpClientRaiseRecord> lastLastLastMpClientRaiseRecords =
                                    mpClientRaiseRecordMapper.selectMpClientRaiseRecordList(lastLastLastMpClientRaiseRecord);

                            //上期成功参与用户按ID分组
                            Map<Long, List<MpClientRaiseRecord>> mapLastLastLast = lastLastLastMpClientRaiseRecords.stream()
                                    .collect(Collectors.groupingBy(MpClientRaiseRecord::getClientId));
                            for (Long keyLast : mapLastLastLast.keySet()){
                                MpClient mpClientLast = mpClientMapper.selectMpClientByClientId(keyLast);
                                List<MpClientRaiseRecord> myRecordLast = mapLastLastLast.get(keyLast);
                                BigDecimal myTakeSum = myRecordLast.stream().map( MpClientRaiseRecord:: getTakeAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
                                mpClientLast.setGoldBeanBalance(mpClientLast.getGoldBeanBalance()==null?new BigDecimal(0):
                                        mpClientLast.getGoldBeanBalance().add(myTakeSum.multiply(lockGoldRate).setScale( 2, BigDecimal.ROUND_HALF_UP )));
                                mpClientLast.setSilverBeanBalance(mpClientLast.getSilverBeanBalance()==null?new BigDecimal(0):
                                        mpClientLast.getSilverBeanBalance().add(myTakeSum.multiply(lockSilverRate).setScale( 2, BigDecimal.ROUND_HALF_UP )));
                                mpClientMapper.updateMpClient(mpClientLast);

                                //增加用户金藻收益记录
                                MpIncomeRecord mpIncomeRecord = new MpIncomeRecord();
                                mpIncomeRecord.setIsIncome(1l);
                                mpIncomeRecord.setType(1l);
                                mpIncomeRecord.setCreateTime(now);
                                mpIncomeRecord.setClientId(mpClientLast.getClientId());
                                mpIncomeRecord.setContent(raise.getRaiseName()+"第"+raise.getListCount()+"期"+"活动失败返还参与金藻");
                                mpIncomeRecord.setAmount(myTakeSum.multiply(lockGoldRate).setScale( 2, BigDecimal.ROUND_HALF_UP ));
                                mpIncomeRecord.setCurrentBalance(mpClientLast.getGoldBeanBalance());
                                mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecord);

                                //增加用户金藻收益记录
                                MpIncomeRecord mpIncomeRecordS = new MpIncomeRecord();
                                mpIncomeRecordS.setIsIncome(1l);
                                mpIncomeRecordS.setType(2l);
                                mpIncomeRecordS.setCreateTime(now);
                                mpIncomeRecordS.setClientId(mpClientLast.getClientId());
                                mpIncomeRecordS.setContent(raise.getRaiseName()+"第"+raise.getListCount()+"期"+"活动失败返还银藻");
                                mpIncomeRecordS.setAmount(myTakeSum.multiply(lockSilverRate).setScale( 2, BigDecimal.ROUND_HALF_UP ));
                                mpIncomeRecordS.setCurrentBalance(mpClientLast.getGoldBeanBalance());
                                mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecordS);

                                //更新上期用户参与记录表
                                for (MpClientRaiseRecord r:myRecordLast) {
                                    r.setSettlementTime(now);
                                    r.setGetGoldAmount(myTakeSum.multiply(lockGoldRate).setScale( 2, BigDecimal.ROUND_HALF_UP ));
                                    r.setGetSilverAmount(myTakeSum.multiply(lockSilverRate).setScale( 2, BigDecimal.ROUND_HALF_UP ));
//                                r.setIsSettleEarns(1);
                                    mpClientRaiseRecordMapper.updateMpClientRaiseRecord(r);
                                }
                            }
                        }else{
                            //do nothing
                        }

                    }else{
                        //do nothing
                    }

                }else {
                    //上期活动失败,分红池无累积金额
                    for (Long key : map.keySet()){
                        //分红池金额为0,返还用户参与的金额
                        MpClient mpClient = mpClientMapper.selectMpClientByClientId(key);
                        List<MpClientRaiseRecord> myRecord = map.get(key);
                        BigDecimal myTakeSum = myRecord.stream().map( MpClientRaiseRecord:: getTakeAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
                        mpClient.setGoldBeanBalance(mpClient.getGoldBeanBalance()==null?new BigDecimal(0):
                                mpClient.getGoldBeanBalance().add(myTakeSum.multiply(nowGoldRate).setScale( 2, BigDecimal.ROUND_HALF_UP )));
                        mpClientMapper.updateMpClient(mpClient);
                        //增加用户金藻收益记录
                        MpIncomeRecord mpIncomeRecord = new MpIncomeRecord();
                        mpIncomeRecord.setIsIncome(1l);
                        mpIncomeRecord.setType(1l);
                        mpIncomeRecord.setCreateTime(now);
                        mpIncomeRecord.setClientId(mpClient.getClientId());
                        mpIncomeRecord.setContent(raise.getRaiseName()+"第"+raise.getListCount()+"期"+"活动失败返还参与金藻");
                        mpIncomeRecord.setAmount(myTakeSum.multiply(nowGoldRate).setScale( 2, BigDecimal.ROUND_HALF_UP ));
                        mpIncomeRecord.setCurrentBalance(mpClient.getGoldBeanBalance());
                        mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecord);
                        //更新用户参与记录表
                        for (MpClientRaiseRecord r:myRecord) {
                            r.setSettlementTime(now);
                            r.setGetGoldAmount(r.getTakeAmount().multiply(nowGoldRate).setScale( 2, BigDecimal.ROUND_HALF_UP ));
                            r.setGetSilverAmount(new BigDecimal(0));
//                        r.setIsSettleEarns(1);
                            mpClientRaiseRecordMapper.updateMpClientRaiseRecord(r);
                        }
                    }
                }
                //更新活动信息
                raise.setIsSuccess(0);
                raise.setIsOver(1);
                pcRaiseMapper.updatePcRaise(raise);
                //增加一条活动失败记录
                PcRaiseRecord insRaiseRecord = new PcRaiseRecord();
                insRaiseRecord.setRaiseType(raise.getRaiseType());
                insRaiseRecord.setSettleTime(now);
                insRaiseRecord.setRaiseId(raise.getId());
                insRaiseRecord.setIsSuccess(0);
                insRaiseRecord.setShareAmount(new BigDecimal(0));
                insRaiseRecord.setAddShareAmount(new BigDecimal(0));
                insRaiseRecord.setCreateTime(now);
                pcRaiseRecordMapper.insertPcRaiseRecord(insRaiseRecord);
                //将同类型后期活动全都失效,并添加记录,并返还用户预购的金额
                // TODO: 2022/8/5
                PcRaise pcRaiseS = new PcRaise();
                pcRaiseS.setStartTime(raise.getStartTime());
                pcRaiseS.setRaiseType(raise.getRaiseType());
                List<PcRaise> nextRaise = pcRaiseMapper.selectPcRaiseNextAllByType(pcRaiseS);
                for (PcRaise pcRaise:nextRaise) {
                    pcRaise.setIsAble(0);
                    pcRaiseMapper.updatePcRaise(pcRaise);
                    //返还参与该期用户所有金藻和银藻。
                    MpClientRaiseRecord clientRaiseRecordNext = new MpClientRaiseRecord();
                    clientRaiseRecordNext.setRaiseId(pcRaise.getId());
                    List<MpClientRaiseRecord> clientsNext = mpClientRaiseRecordMapper.selectMpClientRaiseRecordList(clientRaiseRecordNext);
                    for (MpClientRaiseRecord raiseRecord:clientsNext) {
                        raiseRecord.setIsRaiseAble(0);
//                    raiseRecord.setIsSettleEarns(1);
                        raiseRecord.setReturnGoldAmount(raiseRecord.getOrderAmount());
                        raiseRecord.setReturnSilverAmount(raiseRecord.getFirstOrderSilverAmount());
                        mpClientRaiseRecordMapper.updateMpClientRaiseRecord(raiseRecord);
                        MpClient client = mpClientMapper.selectMpClientByClientId(raiseRecord.getClientId());
                        client.setGoldBeanBalance(client.getGoldBeanBalance()==null?new BigDecimal(0):
                                client.getGoldBeanBalance().add(raiseRecord.getOrderAmount()==null?new BigDecimal(0):raiseRecord.getOrderAmount()));
                        client.setSilverBeanBalance(client.getSilverBeanBalance()==null?new BigDecimal(0):
                                client.getSilverBeanBalance().add(raiseRecord.getFirstOrderSilverAmount()==null?new BigDecimal(0):raiseRecord.getFirstOrderSilverAmount()));
                        mpClientMapper.updateMpClient(client);
                        //增加用户金藻收益记录
                        MpIncomeRecord mpIncomeRecord = new MpIncomeRecord();
                        mpIncomeRecord.setIsIncome(1l);
                        mpIncomeRecord.setType(1l);
                        mpIncomeRecord.setCreateTime(now);
                        mpIncomeRecord.setClientId(client.getClientId());
                        mpIncomeRecord.setContent(raise.getRaiseName()+"第"+raise.getListCount()+"期"+"活动预购金藻返还");
                        mpIncomeRecord.setAmount(raiseRecord.getOrderAmount());
                        mpIncomeRecord.setCurrentBalance(client.getGoldBeanBalance());
                        mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecord);
                        //增加用户金藻收益记录
                        if(raiseRecord.getFirstOrderSilverAmount()!=null&&raiseRecord.getFirstOrderSilverAmount().compareTo(new BigDecimal(0))>0){
                            MpIncomeRecord mpIncomeRecordS = new MpIncomeRecord();
                            mpIncomeRecordS.setIsIncome(1l);
                            mpIncomeRecordS.setType(2l);
                            mpIncomeRecordS.setCreateTime(now);
                            mpIncomeRecordS.setClientId(client.getClientId());
                            mpIncomeRecordS.setContent(raise.getRaiseName()+"第"+raise.getListCount()+"期"+"活动优先预购银藻返还");
                            mpIncomeRecordS.setAmount(raiseRecord.getFirstOrderSilverAmount());
                            mpIncomeRecordS.setCurrentBalance(client.getSilverBeanBalance());
                            mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecordS);
                        }
                    }
                }

            }else {
                //活动成功,返还前第三期活动用户110%参与金额。
                // 获取活动上期奖金池累积金额
//                PcRaiseRecord pcRaiseRecord = new PcRaiseRecord();
//                pcRaiseRecord.setRaiseType(raise.getRaiseType());
//                pcRaiseRecord.setSettleTime(raise.getContinueTime());
//                PcRaiseRecord lastRecord = pcRaiseRecordMapper.selectLastSuccessPcRaiseRecord(pcRaiseRecord);
//                if (lastRecord != null && lastRecord.getIsSuccess() == 1) {
//                    PcRaiseRecord pcRaiseRecordLast = new PcRaiseRecord();
//                    pcRaiseRecordLast.setRaiseType(lastRecord.getRaiseType());
//                    pcRaiseRecordLast.setSettleTime(lastRecord.getSettleTime());
//                    PcRaiseRecord lastLastRecord = pcRaiseRecordMapper.selectLastSuccessPcRaiseRecord(pcRaiseRecordLast);
//                    if (lastLastRecord.getIsSuccess() == 1) {
//                        PcRaiseRecord pcRaiseRecordLastLast = new PcRaiseRecord();
//                        pcRaiseRecordLastLast.setRaiseType(lastLastRecord.getRaiseType());
//                        pcRaiseRecordLastLast.setSettleTime(lastLastRecord.getSettleTime());
//                        PcRaiseRecord lastLastLastRecord = pcRaiseRecordMapper.selectLastSuccessPcRaiseRecord(pcRaiseRecordLastLast);
//                        PcRaise pcRaise = pcRaiseMapper.selectPcRaiseById(lastLastLastRecord.getRaiseId());
//                        BigDecimal earnRate = pcRaise.getEarnRate();
//                        if (lastLastLastRecord != null && lastLastLastRecord.getIsSuccess() == 1) {
//                            //获取上上上期活动参与用户,分发10%+本金收益给对应用户
//                            MpClientRaiseRecord lastLastLastMpClientRaiseRecord = new MpClientRaiseRecord();
//                            lastLastLastMpClientRaiseRecord.setRaiseId(lastLastLastRecord.getRaiseId());
//                            List<MpClientRaiseRecord> lastLastLastMpClientRaiseRecords =
//                                    mpClientRaiseRecordMapper.selectMpClientRaiseRecordList(lastLastLastMpClientRaiseRecord);
//
//                            //上期成功参与用户按ID分组
//                            Map<Long, List<MpClientRaiseRecord>> mapLastLastLast = lastLastLastMpClientRaiseRecords.stream()
//                                    .collect(Collectors.groupingBy(MpClientRaiseRecord::getClientId));
//                            for (Long keyLast : mapLastLastLast.keySet()) {
//                                MpClient mpClientLast = mpClientMapper.selectMpClientByClientId(keyLast);
//                                List<MpClientRaiseRecord> myRecordLast = mapLastLastLast.get(keyLast);
//                                BigDecimal myTakeSum = myRecordLast.stream().map(MpClientRaiseRecord::getTakeAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
//                                //判断用户是否使用了3倍卡或者5倍卡
//
//                                mpClientLast.setGoldBeanBalance(mpClientLast.getGoldBeanBalance() == null ? new BigDecimal(0) :
//                                        mpClientLast.getGoldBeanBalance().add(myTakeSum.multiply(earnRate.add(new BigDecimal(1))).setScale(2, BigDecimal.ROUND_HALF_UP)));
//                                mpClientMapper.updateMpClient(mpClientLast);
//                                //增加用户金藻收益记录
//                                MpIncomeRecord mpIncomeRecord = new MpIncomeRecord();
//                                mpIncomeRecord.setIsIncome(1l);
//                                mpIncomeRecord.setType(1l);
//                                mpIncomeRecord.setCreateTime(now);
//                                mpIncomeRecord.setClientId(mpClientLast.getClientId());
//                                mpIncomeRecord.setContent(raise.getRaiseName() + "活动成功金藻收益");
//                                mpIncomeRecord.setAmount(myTakeSum.multiply(earnRate.add(new BigDecimal(1))).setScale(2, BigDecimal.ROUND_HALF_UP));
//                                mpIncomeRecord.setCurrentBalance(mpClientLast.getGoldBeanBalance());
//                                mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecord);
//                                for (MpClientRaiseRecord r : myRecordLast) {
//                                    r.setSettlementTime(now);
//                                    r.setGetGoldAmount(myTakeSum.multiply(earnRate.add(new BigDecimal(1))).setScale(2, BigDecimal.ROUND_HALF_UP));
////                                r.setIsSettleEarns(1);
//                                    mpClientRaiseRecordMapper.updateMpClientRaiseRecord(r);
//                                }
//                            }
//                            //获取之前参与定返活动的用户,给他们发放对应3%奖励的分红,至到满用户参与的金额。
//                            MpClientReturnRecord selectRecord = new MpClientReturnRecord();
//                            selectRecord.setTakeTime(now);
//                            BigDecimal allMount = raise.getTotalAmount();
//                            List<MpClientReturnRecord> returnRecords = mpClientReturnRecordMapper.selectMpClientReturnRecordListBeForeTime(selectRecord);
//                            for (MpClientReturnRecord returnRecord : returnRecords) {
//                                PcReturnConfig returnConfig = pcReturnConfigMapper.selectPcReturnConfigById(returnRecord.getReturnId());
//                                BigDecimal returnAllAmount = allMount.multiply(returnConfig.getReturnRate()).setScale(2, BigDecimal.ROUND_HALF_UP);
//                                BigDecimal myReturnAmount = returnAllAmount.multiply(new BigDecimal(returnRecord.getBuyPartCount() / returnConfig.getTotalPart())).setScale(2, BigDecimal.ROUND_HALF_UP);
//                                if (returnRecord.getHaveReturnAmount().add(myReturnAmount).compareTo(returnRecord.getTakeAmount()) > 0) {
//                                    myReturnAmount = returnRecord.getTakeAmount().subtract(returnRecord.getHaveReturnAmount());
//                                }
//                                //增加一条用户定返记录
//                                PcClientReturnRecord pcClientReturnRecord = new PcClientReturnRecord();
//                                pcClientReturnRecord.setClientReturnRecordId(returnRecord.getId());
//                                pcClientReturnRecord.setReturnDate(now);
//                                pcClientReturnRecord.setReturnAmount(myReturnAmount);
//                                pcClientReturnRecordMapper.insertPcClientReturnRecord(pcClientReturnRecord);
//
//                                returnRecord.setHaveReturnAmount(returnRecord.getHaveReturnAmount().add(myReturnAmount));
//                                if (returnRecord.getHaveReturnAmount().compareTo(returnRecord.getTakeAmount()) >= 0) {
//                                    returnRecord.setIsSettle(1);
//                                } else {
//                                    returnRecord.setIsSettle(0);
//                                }
//                                mpClientReturnRecordMapper.updateMpClientReturnRecord(returnRecord);
//
//                                //修改用户的金藻余额
//                                MpClient me = mpClientMapper.selectMpClientByClientId(returnRecord.getClientId());
//                                me.setGoldBeanBalance(me.getGoldBeanBalance().add(myReturnAmount));
//                                mpClientMapper.updateMpClient(me);
//                                //增加一条用户收益记录
//                                MpIncomeRecord mpIncomeRecord = new MpIncomeRecord();
//                                mpIncomeRecord.setIsIncome(1l);
//                                mpIncomeRecord.setType(1l);
//                                mpIncomeRecord.setCreateTime(now);
//                                mpIncomeRecord.setAmount(myReturnAmount);
//                                mpIncomeRecord.setCurrentBalance(me.getGoldBeanBalance());
//                                mpIncomeRecord.setContent(returnConfig.getReturnName() + "金藻返还");
//                                mpIncomeRecord.setClientId(me.getClientId());
//                                mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecord);
//                            }
//                        } else {
//                            //do nothing
//                        }
//                    }
//                }
                raise.setIsSuccess(1);
                raise.setIsOver(1);
                pcRaiseMapper.updatePcRaise(raise);
                //增加一条活动成功记录
                //获取奖金分红池比例
//                PcRaiseSystemConfig pcRaiseSystemConfig = new PcRaiseSystemConfig();
//                List<PcRaiseSystemConfig> configs = pcRaiseSystemConfigMapper.selectPcRaiseSystemConfigList(pcRaiseSystemConfig);
//                PcRaiseRecord insRaiseRecord = new PcRaiseRecord();
//                insRaiseRecord.setRaiseType(raise.getRaiseType());
//                insRaiseRecord.setSettleTime(new Date());
//                insRaiseRecord.setRaiseId(raise.getId());
//                insRaiseRecord.setIsSuccess(1);
//                insRaiseRecord.setShareAmount(raise.getTotalAmount().multiply(configs.get(0).getShareRate()).setScale(2, BigDecimal.ROUND_HALF_UP));
//                if(lastRecord!=null){
//                    insRaiseRecord.setAddShareAmount(lastRecord.getAddShareAmount().add(raise.getTotalAmount().multiply(configs.get(0).getShareRate()).setScale(2, BigDecimal.ROUND_HALF_UP)));
//                }else{
//                    insRaiseRecord.setAddShareAmount(raise.getTotalAmount().multiply(configs.get(0).getShareRate().setScale(2, BigDecimal.ROUND_HALF_UP)));
//                }
//                insRaiseRecord.setCreateTime(new Date());
//                pcRaiseRecordMapper.insertPcRaiseRecord(insRaiseRecord);
                pcRaiseConfigService.addNewRaiseByConfig();

            }
            //删除redis缓存
            redisService.deleteObject("RAISE_"+type+"_"+time);
        }

    }
    @Override
    public void settleSucByOverTime() {
             Date now = new Date();
            //获取最新一期活动结束时间

             List<PcRaiseConfig> configss = pcRaiseConfigMapper.selectPcRaiseConfigListAble();
            for (PcRaiseConfig pcRaiseConfig:configss) {
                PcRaise sRaise = new PcRaise();
                sRaise.setRaiseType(pcRaiseConfig.getRaiseType().longValue());
                PcRaise raise = pcRaiseMapper.selectPcRaiseNewOneByType(sRaise);
                if(raise==null){
                    continue;
                }
                PcRaiseRecord sR = new PcRaiseRecord();
                sR.setRaiseId(raise.getId());
                List<PcRaiseRecord> raiseRecords = pcRaiseRecordMapper.selectPcRaiseRecordList(sR);
                if(raiseRecords.size()!=0){
                    continue;
                }
                //获取参与该期活动用户,判断是否众筹成功
                MpClientRaiseRecord mpClientRaiseRecord = new MpClientRaiseRecord();
                mpClientRaiseRecord.setRaiseId(raise.getId());
                List<MpClientRaiseRecord> mpClientRaiseRecords =
                        mpClientRaiseRecordMapper.selectMpClientRaiseRecordList(mpClientRaiseRecord);
                //获取用户参与的总金额(包括预购和现购)
                BigDecimal takeSum = mpClientRaiseRecords.stream().map( MpClientRaiseRecord:: getTakeAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型

                if(raise.getTotalAmount().compareTo(takeSum)>0){

                }else {
                    System.out.println("sss"+raise.getStartTime());
                    //活动成功,返还前第三期活动用户110%参与金额。
                    // 获取活动上期奖金池累积金额
                    PcRaiseRecord pcRaiseRecord = new PcRaiseRecord();
                    pcRaiseRecord.setRaiseType(raise.getRaiseType());
                    pcRaiseRecord.setSettleTime(raise.getContinueTime());
                    PcRaiseRecord lastRecord = pcRaiseRecordMapper.selectLastSuccessPcRaiseRecord(pcRaiseRecord);
                    if (lastRecord != null && lastRecord.getIsSuccess() == 1) {
                        PcRaiseRecord pcRaiseRecordLast = new PcRaiseRecord();
                        pcRaiseRecordLast.setRaiseType(lastRecord.getRaiseType());
                        pcRaiseRecordLast.setSettleTime(lastRecord.getSettleTime());
                        PcRaiseRecord lastLastRecord = pcRaiseRecordMapper.selectLastSuccessPcRaiseRecord(pcRaiseRecordLast);
                        if (lastLastRecord!=null&&lastLastRecord.getIsSuccess() == 1) {
                            PcRaiseRecord pcRaiseRecordLastLast = new PcRaiseRecord();
                            pcRaiseRecordLastLast.setRaiseType(lastLastRecord.getRaiseType());
                            pcRaiseRecordLastLast.setSettleTime(lastLastRecord.getSettleTime());
                            PcRaiseRecord lastLastLastRecord = pcRaiseRecordMapper.selectLastSuccessPcRaiseRecord(pcRaiseRecordLastLast);
                            if (lastLastLastRecord != null && lastLastLastRecord.getIsSuccess() == 1) {
                                PcRaise pcRaise = pcRaiseMapper.selectPcRaiseById(lastLastLastRecord.getRaiseId());
                                BigDecimal earnRate = pcRaise.getEarnRate();
                                //获取上上上期活动参与用户,分发10%+本金收益给对应用户
                                MpClientRaiseRecord lastLastLastMpClientRaiseRecord = new MpClientRaiseRecord();
                                lastLastLastMpClientRaiseRecord.setRaiseId(lastLastLastRecord.getRaiseId());
                                List<MpClientRaiseRecord> lastLastLastMpClientRaiseRecords =
                                        mpClientRaiseRecordMapper.selectMpClientRaiseRecordList(lastLastLastMpClientRaiseRecord);

                                //上期成功参与用户按ID分组
                                Map<Long, List<MpClientRaiseRecord>> mapLastLastLast = lastLastLastMpClientRaiseRecords.stream()
                                        .collect(Collectors.groupingBy(MpClientRaiseRecord::getClientId));
                                for (Long keyLast : mapLastLastLast.keySet()) {
                                    MpClient mpClientLast = mpClientMapper.selectMpClientByClientId(keyLast);
                                    List<MpClientRaiseRecord> myRecordLast = mapLastLastLast.get(keyLast);
                                    BigDecimal myTakeSum = myRecordLast.stream().map(MpClientRaiseRecord::getTakeAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
                                    //判断用户是否使用了3倍卡或者5倍卡

                                    mpClientLast.setGoldBeanBalance(mpClientLast.getGoldBeanBalance() == null ? new BigDecimal(0) :
                                            mpClientLast.getGoldBeanBalance().add(myTakeSum.multiply(earnRate.add(new BigDecimal(1))).setScale(2, BigDecimal.ROUND_HALF_UP)));
                                    mpClientMapper.updateMpClient(mpClientLast);
                                    //增加用户金藻收益记录
                                    MpIncomeRecord mpIncomeRecord = new MpIncomeRecord();
                                    mpIncomeRecord.setIsIncome(1l);
                                    mpIncomeRecord.setType(1l);
                                    mpIncomeRecord.setCreateTime(now);
                                    mpIncomeRecord.setClientId(mpClientLast.getClientId());
                                    mpIncomeRecord.setContent(raise.getRaiseName() +"第"+raise.getListCount()+"期"+ "活动成功金藻收益");
                                    mpIncomeRecord.setAmount(myTakeSum.multiply(earnRate).setScale(2, BigDecimal.ROUND_HALF_UP));
                                    mpIncomeRecord.setCurrentBalance(mpClientLast.getGoldBeanBalance());
                                    mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecord);

                                    MpIncomeRecord mpIncomeRecord1= new MpIncomeRecord();
                                    mpIncomeRecord1.setIsIncome(1l);
                                    mpIncomeRecord1.setType(1l);
                                    mpIncomeRecord1.setCreateTime(now);
                                    mpIncomeRecord1.setClientId(mpClientLast.getClientId());
                                    mpIncomeRecord1.setContent(raise.getRaiseName() +"第"+raise.getListCount()+"期"+ "活动成功金藻返还");
                                    mpIncomeRecord1.setAmount(myTakeSum);
                                    mpIncomeRecord1.setCurrentBalance(mpClientLast.getGoldBeanBalance());
                                    mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecord1);
                                    for (MpClientRaiseRecord r : myRecordLast) {
                                        r.setSettlementTime(now);
                                        r.setGetGoldAmount(myTakeSum.multiply(earnRate).setScale(2, BigDecimal.ROUND_HALF_UP));
//                                r.setIsSettleEarns(1);
                                        mpClientRaiseRecordMapper.updateMpClientRaiseRecord(r);
                                    }
                                    countEarns(myRecordLast);
                                }
                                //获取之前参与定返活动的用户,给他们发放对应3%奖励的分红,至到满用户参与的金额。
                                MpClientReturnRecord selectRecord = new MpClientReturnRecord();
                                selectRecord.setTakeTime(now);
                                BigDecimal allMount = raise.getTotalAmount();
                                List<MpClientReturnRecord> returnRecords = mpClientReturnRecordMapper.selectMpClientReturnRecordListBeForeTime(selectRecord);
                                for (MpClientReturnRecord returnRecord : returnRecords) {
                                    PcReturnConfig returnConfig = pcReturnConfigMapper.selectPcReturnConfigById(returnRecord.getReturnId());
                                    BigDecimal returnAllAmount = allMount.multiply(returnConfig.getReturnRate()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    BigDecimal myReturnAmount = returnAllAmount.multiply(new BigDecimal(returnRecord.getBuyPartCount() / returnConfig.getTotalPart())).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    if (returnRecord.getHaveReturnAmount().add(myReturnAmount).compareTo(returnRecord.getTakeAmount()) > 0) {
                                        myReturnAmount = returnRecord.getTakeAmount().subtract(returnRecord.getHaveReturnAmount());
                                    }
                                    //增加一条用户定返记录
                                    PcClientReturnRecord pcClientReturnRecord = new PcClientReturnRecord();
                                    pcClientReturnRecord.setClientReturnRecordId(returnRecord.getId());
                                    pcClientReturnRecord.setReturnDate(now);
                                    pcClientReturnRecord.setReturnAmount(myReturnAmount);
                                    pcClientReturnRecordMapper.insertPcClientReturnRecord(pcClientReturnRecord);

                                    returnRecord.setHaveReturnAmount(returnRecord.getHaveReturnAmount().add(myReturnAmount));
                                    if (returnRecord.getHaveReturnAmount().compareTo(returnRecord.getTakeAmount()) >= 0) {
                                        returnRecord.setIsSettle(1);
                                    } else {
                                        returnRecord.setIsSettle(0);
                                    }
                                    mpClientReturnRecordMapper.updateMpClientReturnRecord(returnRecord);

                                    //修改用户的金藻余额
                                    MpClient me = mpClientMapper.selectMpClientByClientId(returnRecord.getClientId());
                                    me.setGoldBeanBalance(me.getGoldBeanBalance().add(myReturnAmount));
                                    mpClientMapper.updateMpClient(me);
                                    //增加一条用户收益记录
                                    MpIncomeRecord mpIncomeRecord = new MpIncomeRecord();
                                    mpIncomeRecord.setIsIncome(1l);
                                    mpIncomeRecord.setType(1l);
                                    mpIncomeRecord.setCreateTime(now);
                                    mpIncomeRecord.setAmount(myReturnAmount);
                                    mpIncomeRecord.setCurrentBalance(me.getGoldBeanBalance());
                                    mpIncomeRecord.setContent(returnConfig.getReturnName() + "金藻返还");
                                    mpIncomeRecord.setClientId(me.getClientId());
                                    mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecord);
                                }
                            } else {
                                //do nothing
                            }
                        }
                    }
//                raise.setIsSuccess(1);
//                raise.setIsOver(1);
//                pcRaiseMapper.updatePcRaise(raise);
                    //增加一条活动成功记录
                    //获取奖金分红池比例
                    PcRaiseSystemConfig pcRaiseSystemConfig = new PcRaiseSystemConfig();
                    List<PcRaiseSystemConfig> configs = pcRaiseSystemConfigMapper.selectPcRaiseSystemConfigList(pcRaiseSystemConfig);
                    PcRaiseRecord insRaiseRecord = new PcRaiseRecord();
                    insRaiseRecord.setRaiseType(raise.getRaiseType());
                    insRaiseRecord.setSettleTime(new Date());
                    insRaiseRecord.setRaiseId(raise.getId());
                    insRaiseRecord.setIsSuccess(1);
                    insRaiseRecord.setShareAmount(raise.getTotalAmount().multiply(configs.get(0).getShareRate()).setScale(2, BigDecimal.ROUND_HALF_UP));
                    if(lastRecord!=null){
                        insRaiseRecord.setAddShareAmount(lastRecord.getAddShareAmount().add(raise.getTotalAmount().multiply(configs.get(0).getShareRate()).setScale(2, BigDecimal.ROUND_HALF_UP)));
                    }else{
                        insRaiseRecord.setAddShareAmount(raise.getTotalAmount().multiply(configs.get(0).getShareRate().setScale(2, BigDecimal.ROUND_HALF_UP)));
                    }
                    insRaiseRecord.setCreateTime(new Date());
                    pcRaiseRecordMapper.insertPcRaiseRecord(insRaiseRecord);
                }
            }


    }
    @Override
    public PcRaise getNewOne() {
        PcRaise raise = pcRaiseMapper.selectPcRaiseNewOne();
        return raise;
    }

    @Override
    public void countEarns(List<MpClientRaiseRecord> raiseRecords) {
        List<PcDistributionConfig> distributionConfigs = pcDistributionConfigMapper.selectPcDistributionConfigList(new PcDistributionConfig());
        BigDecimal teamRate = distributionConfigs.get(0).getTeamSameLevelRate();
        BigDecimal directRate = distributionConfigs.get(0).getDirectRecommendRate();
        BigDecimal inDirectRate = distributionConfigs.get(0).getIndirectRecommendRate();
        //获取所有已结算收益但未结算业绩收益的用户记录
//        List<MpClientRaiseRecord> raiseRecords = mpClientRaiseRecordMapper.selectMpClientRaiseRecordNoSettleEarns();
        //参与用户按ID分组
        Map<Long, List<MpClientRaiseRecord>> map = raiseRecords.stream()
                .collect(Collectors.groupingBy(MpClientRaiseRecord::getClientId));
        for (Long key : map.keySet()){
            List<MpClientRaiseRecord> myRecord = map.get(key);
            MpClientRaiseRecord raiseRecord = myRecord.get(0);
            BigDecimal myEarns = myRecord.stream().map( MpClientRaiseRecord:: getTakeAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
                String myLevel = null;
                PcRaise raise =  pcRaiseMapper.selectPcRaiseById(raiseRecord.getRaiseId());
                if(raise.getIsSuccess()!=1){
                    continue;
                }
                //获取用户余额
                MpClient me = mpClientMapper.selectMpClientByClientId(raiseRecord.getClientId());


                Long childId = key;
                MpClientFriends mpFriends = new MpClientFriends();
                mpFriends.setClienId(childId);
                List<MpClientFriends> fList = mpClientFriendsMapper.selectMpClientFriendsList(mpFriends);
                List<Long> ids = getUserIds(fList);
                //查询出所有父ID,根据所有父用户等级计算收益
                String teamLevel = "0";
                //是否平级
                Boolean isPeers = false;
                BigDecimal childTeamEarns= new BigDecimal(0);
                int i = 0;
                Boolean isCenter = false;
                for (Long id: ids) {
                    //更新用户金额
                    i++;
                    // TODO: 2022/8/4
                    MpClient  mpClient =  mpClientMapper.selectMpClientByClientId(id);
                    if(mpClient.getGoldBeanBalance()==null){
                        mpClient.setGoldBeanBalance(new BigDecimal("0"));
                    }
                    //获取用户参与游戏未计算收益的金额
                    MpClientRaiseRecord raiseRecord1 =  new MpClientRaiseRecord();
                    raiseRecord1.setClientId(mpClient.getClientId());
                    List<MpClientRaiseRecord> myList =  mpClientRaiseRecordMapper.selectMpClientRaiseRecordNowTake(raiseRecord1);
                    BigDecimal myTakeSum = myList.stream().map( MpClientRaiseRecord:: getTakeAmount).reduce(BigDecimal.ZERO, BigDecimal::add); //BigDecimal类型
                    BigDecimal myAllGold = mpClient.getGoldBeanBalance()==null?new BigDecimal("0"):me.getGoldBeanBalance().add(myTakeSum);
                    //资产是否低于最低预留资产
                    Boolean isFake = false;
                    if(mpClient.getTeamConfigId()!=null&&mpClient.getTeamConfigId()!=0){
                        PcTeamConfig teamConfig = pcTeamConfigMapper.selectPcTeamConfigById(mpClient.getTeamConfigId());
                        if(teamConfig.getMinReservedGold().compareTo(myAllGold)>0){
                            isFake= true;
                        }
                    }
                    if(i==1){
                        //直推收取1%收益
                        BigDecimal addEarns = myEarns.multiply(directRate).setScale( 2, BigDecimal.ROUND_HALF_UP );
                        mpClient.setGoldBeanBalance(mpClient.getGoldBeanBalance().add(addEarns));
                        //增加用户业绩收益记录
                        MpClientEarns mpClientEarns = new MpClientEarns();
                        mpClientEarns.setClientId(id);
                        mpClientEarns.setChildId(childId);
                        mpClientEarns.setChildAmount(myEarns);
                        mpClientEarns.setShouldAmount(addEarns);
                        mpClientEarns.setCreateTime(new Date());
                        mpClientEarns.setContent("直推收益");
                        mpClientEarns.setEarnsType(1);
                        if(isFake){
                            mpClientEarns.setClientEarns(new BigDecimal(0));
                            mpClientEarns.setIsAble(0);
                        }else{
                            mpClientEarns.setClientEarns(addEarns);
                            mpClientEarns.setIsAble(1);
                        }
                        mpClientEarnsMapper.insertMpClientEarns(mpClientEarns);
                        if(!isFake){
                            //增加用户收益记录
                            MpIncomeRecord mpIncomeRecord = new MpIncomeRecord();
                            mpIncomeRecord.setType(1l);
                            mpIncomeRecord.setIsIncome(1l);
                            mpIncomeRecord.setCreateTime(new Date());
                            mpIncomeRecord.setClientId(id);
                            mpIncomeRecord.setContent("直推收益");
                            mpIncomeRecord.setAmount(addEarns);
                            mpIncomeRecord.setCurrentBalance(mpClient.getGoldBeanBalance());
                            mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecord);
                        }
                        mpClientMapper.updateMpClient(mpClient);
                        if(mpClient.getIsVirtual()==3){
                            continue;
                        }
                    }
                    if(i==2){
                        //荐推收取2%收益
                        BigDecimal addEarns = myEarns.multiply(inDirectRate);
                        mpClient.setGoldBeanBalance(mpClient.getGoldBeanBalance().add(addEarns));
                        //增加用户业绩收益记录
                        MpClientEarns mpClientEarns = new MpClientEarns();
                        mpClientEarns.setClientId(id);
                        mpClientEarns.setChildId(childId);
                        mpClientEarns.setChildAmount(myEarns);
                        mpClientEarns.setShouldAmount(addEarns);
                        mpClientEarns.setCreateTime(new Date());
                        mpClientEarns.setContent("间推收益");
                        mpClientEarns.setEarnsType(2);
                        if(isFake){
                            mpClientEarns.setClientEarns(new BigDecimal(0));
                            mpClientEarns.setIsAble(0);
                        }else{
                            mpClientEarns.setClientEarns(addEarns);
                            mpClientEarns.setIsAble(1);
                        }
                        mpClientEarnsMapper.insertMpClientEarns(mpClientEarns);
                        if(!isFake){
                            //增加用户收益记录
                            MpIncomeRecord mpIncomeRecord = new MpIncomeRecord();
                            mpIncomeRecord.setType(1l);
                            mpIncomeRecord.setIsIncome(1l);
                            mpIncomeRecord.setCreateTime(new Date());
                            mpIncomeRecord.setClientId(id);
                            mpIncomeRecord.setContent("间推收益");
                            mpIncomeRecord.setAmount(addEarns);
                            mpIncomeRecord.setCurrentBalance(mpClient.getGoldBeanBalance());
                            mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecord);
                        }
                        mpClientMapper.updateMpClient(mpClient);
                        if(mpClient.getIsVirtual()==3){
                            continue;
                        }
                    }
                    //计算团队收益
                    if(mpClient.getTeamConfigId()!=null&&mpClient.getTeamConfigId()!=0&&mpClient.getIsVirtual()!=3){
                        PcTeamConfig myTeam = pcTeamConfigMapper.selectPcTeamConfigById(mpClient.getTeamConfigId());
                        myLevel = myTeam.getSort().toString();
                        BigDecimal myRewardRate = myTeam.getRewardRate();
                        if(teamLevel.equals("0")){
                            //获取到第一次上级V1
                            teamLevel = myLevel;
                            BigDecimal addEarns = myEarns.multiply(myRewardRate);
                            mpClient.setGoldBeanBalance(mpClient.getGoldBeanBalance().add(addEarns));
                            isPeers =true;

                            //增加用户业绩收益记录
                            MpClientEarns mpClientEarns = new MpClientEarns();
                            mpClientEarns.setClientId(id);
                            mpClientEarns.setChildId(childId);
                            mpClientEarns.setChildAmount(myEarns);
                            mpClientEarns.setShouldAmount(addEarns);
                            mpClientEarns.setCreateTime(new Date());
                            mpClientEarns.setContent("团队收益");
                            mpClientEarns.setEarnsType(3);
                            if(isFake){
                                mpClientEarns.setClientEarns(new BigDecimal(0));
                                mpClientEarns.setIsAble(0);
                            }else{
                                mpClientEarns.setClientEarns(addEarns);
                                mpClientEarns.setIsAble(1);
                            }
                            mpClientEarnsMapper.insertMpClientEarns(mpClientEarns);
                            if(!isFake){
                                //增加用户收益记录
                                MpIncomeRecord mpIncomeRecord = new MpIncomeRecord();
                                mpIncomeRecord.setType(1l);
                                mpIncomeRecord.setIsIncome(1l);
                                mpIncomeRecord.setCreateTime(new Date());
                                mpIncomeRecord.setClientId(id);
                                mpIncomeRecord.setContent("团队收益");
                                mpIncomeRecord.setAmount(addEarns);
                                mpIncomeRecord.setCurrentBalance(mpClient.getGoldBeanBalance());
                                mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecord);
                            }
                            mpClientMapper.updateMpClient(mpClient);
                            continue;
                        }
                        if(myLevel.equals(teamLevel)&&isPeers){
                            //获取到第二次上级V1,算平级奖励
                            teamLevel = myLevel;
                            BigDecimal addEarns = myEarns.multiply(teamRate);
                            mpClient.setGoldBeanBalance(mpClient.getGoldBeanBalance().add(addEarns));
                            isPeers=false;
                            //增加用户业绩收益记录
                            MpClientEarns mpClientEarns = new MpClientEarns();
                            mpClientEarns.setClientId(id);
                            mpClientEarns.setChildId(childId);
                            mpClientEarns.setChildAmount(myEarns);
                            mpClientEarns.setCreateTime(new Date());
                            mpClientEarns.setContent("团队收益(平级)");
                            mpClientEarns.setShouldAmount(addEarns);
                            mpClientEarns.setEarnsType(3);
                            if(isFake){
                                mpClientEarns.setClientEarns(new BigDecimal(0));
                                mpClientEarns.setIsAble(0);
                            }else{
                                mpClientEarns.setClientEarns(addEarns);
                                mpClientEarns.setIsAble(1);
                            }
                            mpClientEarnsMapper.insertMpClientEarns(mpClientEarns);
                            if(!isFake){
                                //增加用户收益记录
                                MpIncomeRecord mpIncomeRecord = new MpIncomeRecord();
                                mpIncomeRecord.setType(1l);
                                mpIncomeRecord.setIsIncome(1l);
                                mpIncomeRecord.setCreateTime(new Date());
                                mpIncomeRecord.setClientId(id);
                                mpIncomeRecord.setContent("团队收益");
                                mpIncomeRecord.setAmount(addEarns);
                                mpIncomeRecord.setCurrentBalance(mpClient.getGoldBeanBalance());
                                mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecord);
                            }
                            mpClientMapper.updateMpClient(mpClient);
                            continue;
                        }
                        if(!teamLevel.equals("0")&&Integer.valueOf(myLevel).intValue()>Integer.valueOf(teamLevel).intValue()){
                            //获取到第一次上级V2,算极差收益
                            PcTeamConfig lastTeam  = new PcTeamConfig();
                            lastTeam.setSort(Integer.valueOf(teamLevel));
                            List<PcTeamConfig> list = pcTeamConfigMapper.selectPcTeamConfigList(lastTeam);
                            BigDecimal addEarns = myEarns.multiply(myRewardRate.subtract(list.get(0).getRewardRate()));
                            mpClient.setGoldBeanBalance(mpClient.getGoldBeanBalance().add(addEarns));
                            if(myLevel.equals("4")||myLevel.equals("5")){
                                isPeers =true;
                            }
                            teamLevel = myLevel;
                            //增加用户业绩收益记录
                            MpClientEarns mpClientEarns = new MpClientEarns();
                            mpClientEarns.setClientId(id);
                            mpClientEarns.setChildId(childId);
                            mpClientEarns.setChildAmount(myEarns);
                            mpClientEarns.setCreateTime(new Date());
                            mpClientEarns.setContent("团队收益(极差)");
                            mpClientEarns.setShouldAmount(addEarns);
                            mpClientEarns.setEarnsType(3);
                            if(isFake){
                                mpClientEarns.setClientEarns(new BigDecimal(0));
                                mpClientEarns.setIsAble(0);
                            }else{
                                mpClientEarns.setClientEarns(addEarns);
                                mpClientEarns.setIsAble(1);
                            }
                            mpClientEarnsMapper.insertMpClientEarns(mpClientEarns);
                            if(!isFake){
                                //增加用户收益记录
                                MpIncomeRecord mpIncomeRecord = new MpIncomeRecord();
                                mpIncomeRecord.setType(1l);
                                mpIncomeRecord.setIsIncome(1l);
                                mpIncomeRecord.setCreateTime(new Date());
                                mpIncomeRecord.setClientId(id);
                                mpIncomeRecord.setContent("团队收益");
                                mpIncomeRecord.setAmount(addEarns);
                                mpIncomeRecord.setCurrentBalance(mpClient.getGoldBeanBalance());
                                mpIncomeRecordMapper.insertMpIncomeRecord(mpIncomeRecord);
                            }
                            mpClientMapper.updateMpClient(mpClient);
                            continue;
                        }

                    }

                }
//            //更新当前业绩用户业绩总额
                me.setMyEarns(new BigDecimal(me.getMyEarns()==null?"0":me.getMyEarns()).add(raiseRecord.getTakeAmount()).toString());
                mpClientMapper.updateMpClient(me);


        }



    }

    //递归出所有用户上级id
    private List<Long> getUserIds(List<MpClientFriends> userIdlist){
        List<Long> ids = new ArrayList<>();
        if(userIdlist!=null && userIdlist.size()>0){
            for(MpClientFriends vo:userIdlist){
                ids.add(vo.getpClientId());
                MpClientFriends parentF = new MpClientFriends();
                parentF.setClienId(vo.getpClientId());
                List<MpClientFriends> childs =mpClientFriendsMapper.selectMpClientFriendsList(parentF);
                ids.addAll(getUserIds(childs));
            }
        }
        return ids;
    }
}
